package cn.com.hfuu.control;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cn.com.hfuu.SystemUtil;
import cn.com.hfuu.UUIdUtil;
import cn.com.hfuu.ViewExcel;
import cn.com.hfuu.module.code;
import cn.com.hfuu.module.land;
import cn.com.hfuu.module.operategz;
import cn.com.hfuu.module.pick;
import cn.com.hfuu.module.user;
import cn.com.hfuu.module.warehouseteax;
import cn.com.hfuu.module.warehouseteaxlog;
import cn.com.hfuu.service.CodeService;
import cn.com.hfuu.service.LandService;
import cn.com.hfuu.service.PickService;
import cn.com.hfuu.service.TeaxService;
import cn.com.hfuu.service.TeaxlogService;
import cn.com.hfuu.service.UserService;
import cn.com.hfuu.vo.Page;

@Controller
@RequestMapping("pick")
public class PickControl {

	@Autowired
	PickService pickservice;

	@Autowired
	CodeService codeservice;

	@Autowired
	UserService userService;

	@Autowired
	TeaxService teaxservice;

	@Autowired
	TeaxlogService teaxlogservice;

	private List<code> czlist;// 采摘方式

	private List<land> landlist;

	private List<user> userlist;

	@Autowired
	LandService landser;

	@RequestMapping("info")
	public String info(Model m) {
		czlist = codeservice.selectbyType("06");
		landlist = landser.selectall();
		userlist = userService.selectall();
		m.addAttribute("land", landlist);
		return "pick/pick";
	}

	@RequestMapping("list")
	@ResponseBody
	public Page list(Integer start, Integer limit, pick p) {
		List<pick> picklist = pickservice.selectpage(start, limit, p);
		List<pick> picktotal = pickservice.selectpagetotal(p);
		for (pick pick : picklist) {
			for (code c : czlist) {
				if (pick.getPickOperate() == c.getCodeValue())
					pick.setCode(c);
			}
			for (land l : landlist) {
				if (l.getLandId().equals(pick.getPickLandid()))
					pick.setLand(l);
			}
			for (user u : userlist) {
				if (u.getUserId().equals(pick.getPickUserid()))
					pick.setUser(u);
			}

			System.out.println(pick.toString());

		}
		Page page = new Page();
		page.setStart(start);
		page.setLimit(limit);
		page.setRoot(picklist);
		page.setTotal(picktotal.size());
		return page;
	}
	
	@RequestMapping("export")
	public ModelAndView export(ModelMap map) {
		pick p=new pick();
		p.setPickLandid("-1");
 		List<pick> list =pickservice.selectpagetotal(p);
		List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
		for (pick pick : list) {
			Map<String, String> map1 = new HashMap<String, String>();
			for (code c : czlist) {
				if (pick.getPickOperate() == c.getCodeValue())
					pick.setCode(c);
			}
			for (land l : landlist) {
				if (l.getLandId().equals(pick.getPickLandid()))
					pick.setLand(l);
			}
			for (user u : userlist) {
				if (u.getUserId().equals(pick.getPickUserid()))
					pick.setUser(u);
			}
			
			map1.put("编号",pick.getPickId());
			map1.put("茶名",pick.getPickTeaname());
			map1.put("茶园名",pick.getLand().getLandName());
			map1.put("重量（克）", pick.getPickQuality()+"");
			map1.put("采摘方式", pick.getCode().getCodeName());
			map1.put("采摘人", pick.getUser().getUserName());
			map1.put("采摘时间",pick.getPickTime());
			mapList.add(map1);

		}
		String[] title = { "编号", "茶名","茶园名","重量（克）", "采摘方式","采摘人", "采摘时间" };
		map.addAttribute("excelList", mapList);
		ViewExcel ve = new ViewExcel(title, "茶叶采摘信息");
		return new ModelAndView(ve, map);
	}

	@RequestMapping("listad")
	@ResponseBody
	public List<pick> listad() {

		List<pick> picktotal = pickservice.selecttotal();

		return picktotal;
	}

	@RequestMapping("add")
	public String add(Model m) {
		m.addAttribute("codelist", czlist);
		m.addAttribute("land", landlist);
		return "pick/add";
	}

	@RequestMapping("addproc")
	@ResponseBody
	public String addproc(pick p, HttpServletRequest req) {
		HttpSession s = req.getSession();
		user u = (user) s.getAttribute("user");
		p.setPickUserid(u.getUserId());
		SystemUtil sys = new SystemUtil();
		UUIdUtil idu = new UUIdUtil();
		p.setPickTime(sys.getDatetime());
		p.setPickId(idu.getUuid());
		System.out.println(p.toString());
		if (pickservice.insert(p) > 0) {
			// 采摘同时插入仓库数据库
			warehouseteax teax = new warehouseteax();
			teax.setWarehouseTeaxid(idu.getUuid());
			teax.setWarehousePickid(p.getPickId());
			teax.setWarehouseTeaname(p.getPickTeaname());
			teax.setWarehouseTeaquality(p.getPickQuality());
			teax.setState(0);
			teaxservice.insert(teax);
			System.out.println(teax.toString());
			// 入库日志记录
			/**/
			return "success";
		}

		return null;

	}

	float q;

	@RequestMapping("edit")
	public ModelAndView edit(String id) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("pick/edit");
		pick p = pickservice.seletbyid(id);
		q = p.getPickQuality();
		mv.addObject("pick", p);
		mv.addObject("codelist", czlist);
		mv.addObject("land", landlist);
		return mv;
	}

	@RequestMapping("editproc")
	@ResponseBody
	public String editproc(pick p) {
		warehouseteax teax = teaxservice.selectbypick(p.getPickId());
		teax.setWarehouseTeaname(p.getPickTeaname());
		teax.setWarehouseTeaquality(teax.getWarehouseTeaquality()
				+ p.getPickQuality() - q);
		if (teax.getWarehouseTeaquality() < 0) {
			return "error";
		}
		if (pickservice.update(p) > 0) {
			teaxservice.update(teax);
			return "success";
		}
		return null;

	}

	/**
	 * 
	 * 安卓客户端访问
	 * 
	 * @param p
	 * @return
	 */

	@RequestMapping("editprocad")
	@ResponseBody
	public String editprocad(@RequestBody pick p) {
		warehouseteax teax = teaxservice.selectbypick(p.getPickId());
		teax.setWarehouseTeaname(p.getPickTeaname());
		teax.setWarehouseTeaquality(teax.getWarehouseTeaquality()
				+ p.getPickQuality() - q);
		if (teax.getWarehouseTeaquality() < 0) {
			return "error";
		}
		if (pickservice.update(p) > 0) {
			teaxservice.update(teax);
			return "success";
		}
		return null;

	}

	@RequestMapping("addprocad")
	@ResponseBody
	public String addprocad(@RequestBody pick p, HttpServletRequest req) {
		HttpSession s = req.getSession();
		user u = (user) s.getAttribute("user");
		p.setPickUserid(u.getUserId());
		SystemUtil sys = new SystemUtil();
		UUIdUtil idu = new UUIdUtil();
		p.setPickTime(sys.getDatetime());
		p.setPickId(idu.getUuid());
		System.out.println(p.toString());
		if (pickservice.insert(p) > 0) {
			// 采摘同时插入仓库数据库
			warehouseteax teax = new warehouseteax();
			teax.setWarehouseTeaxid(idu.getUuid());
			teax.setWarehousePickid(p.getPickId());
			teax.setWarehouseTeaname(p.getPickTeaname());
			teax.setWarehouseTeaquality(p.getPickQuality());
			teax.setState(0);
			teaxservice.insert(teax);
			System.out.println(teax.toString());
			// 入库日志记录
			/*warehouseteaxlog teaxlog = new warehouseteaxlog();
			teaxlog.setWarehouseTeaxlogid(idu.getUuid());
			teaxlog.setWarehouseTeaxid(teax.getWarehouseTeaxid());
			teaxlog.setWarehouseTeaxtype(1);
			teaxlog.setWarehouseUserid(u.getUserId());
			teaxlog.setWarehouseTeaxlogtime(sys.getDatetime());
			teaxlog.setWarehouseTeaxquality(p.getPickQuality());
			teaxlogservice.insert(teaxlog);*/
			return "success";
		}

		return null;

	}

	@RequestMapping("/delete")
	@ResponseBody
	public String delete(String id) {
		pick p = pickservice.seletbyid(id);
		warehouseteax teax = teaxservice.selectbypick(id);
		
		int teaxlog = teaxlogservice.selectbyteaxid(teax.getWarehouseTeaxid());
		if ((Math.abs(p.getPickQuality()-teax.getWarehouseTeaquality())<0.00000001)
				&& (teaxlog == 0)) {
			if (pickservice.delete(id) > 0) {
				teaxservice.delete(teax.getWarehouseTeaxid());
				teaxlogservice.deletebyteaxid(teax.getWarehouseTeaxid());
				
				return "success";
			}
		}
		return "false";

	}
	
	@RequestMapping("/addfile")
	public String addfile() {
		return "pick/addfile";
	}
	@RequestMapping("/mobandown")
	public void usermobandown(HttpServletRequest req,
			HttpServletResponse response) throws Exception {
		String fileName = req.getServletContext().getRealPath("/")
				+ "excel\\采摘模板.xls";
		System.out.println(fileName);

		String filename = "采摘模板.xls";
		// filename = URLEncoder.encode(filename,"UTF-8");
		response.addHeader("Content-Disposition", "attachment;filename="
				+ new String(filename.getBytes(), "ISO8859-1"));
		BufferedOutputStream out = new BufferedOutputStream(
				response.getOutputStream());
		int len = 0;
		InputStream bis = new BufferedInputStream(new FileInputStream(new File(
				fileName)));
		while ((len = bis.read()) != -1) {
			out.write(len);
			out.flush();
		}
		bis.close();
		out.close();

	}
	
	@RequestMapping(value="upload",produces = "application/json;charset=UTF-8")
	@ResponseBody
	public JSONArray userupload(MultipartFile file) throws Exception{
		System.out.println("filename:"+file.getOriginalFilename());
		InputStream in = file.getInputStream();
		String res="导入成功";
		try {
			pickservice.upload(in,file);	
		} catch (Exception e) {
			// TODO: handle exception
			res=e.getMessage();
		}	
		res="[{\"result\":\""+res+"\"}]";
		JSONArray jsonArray = JSONArray.fromObject(res);
		return jsonArray;
	}
}
